//---------------------------------------------------------------------------
#include <vcl.h>
#include <registry.hpp>
#pragma hdrstop
#include <utilcls.h>
#include <eic.h>
#include <FileCtrl.hpp>
#include "EnvoiGED.h"
#include "uEnvoiGED.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "OpenDirectory"
#pragma link "CRadBtn"
#pragma link "CComboBx"
#pragma resource "*.dfm"
//---------------------------------------------------------------------------
#define ColonneMaxGed 5
#define MODULE_TAG 1


TModalResult __fastcall GED_Envoi( Variant *pvGedEIC, WideString &Classement, AnsiString &NomDocument, int &DestGED, AnsiString &NomImprimante, bool &bSepareImpGroupe, bool &bClassementAppliqueAuDocumentCourant, bool pChoixClassementEnsDocsPossible, int pDestGEDPrecedent,int pChoixPossibles )
{
  TModalResult bResult = mrNone;
  TEnvoiGED *frmEnvoiGED;
  bool bCapture = false;
  bSepareImpGroupe = true;

  try{

    if(DestGED == 0)
        frmEnvoiGED = new TEnvoiGED( NULL, pvGedEIC);
    else
        frmEnvoiGED = new TEnvoiGED(NULL,NULL);
//    frmEnvoiGED->m_asNomDoc = EmptyStr;

    if( Classement.IsEmpty())
    {   // Le modèle de classement n'est pas paramétré
      //if(! GED_IsClassAuto())
        bCapture = true;
    }else
    {
      TStringList *Criteres = new TStringList();
      Criteres->CommaText = Classement;
      if( (Criteres->Strings[0] != CLASSEMENT_NON_REMPLI) && (Criteres->Strings[0] != CLASSEMENT_AUTO) && (Criteres->Strings[0] !=CLASSEMENT_MAL_RENSEIGNE))
      {
        int nbCritereValides = 0;

        for(int i = 0; i < Criteres->Count; i++)
        {
          if( !Criteres->Strings[i].IsEmpty())
            nbCritereValides++;
        }

        switch( nbCritereValides)
        {
          case 4 :
          case 5 :
          case 6 : NomImprimante = GED_NomPilote();
                   DestGED       = nbCritereValides;
                   bResult = mrRetry;
            break;
          default :
            if( nbCritereValides < 4)
            {
              AnsiString s = "Les paramètres de classement :";
              if( (Criteres->Count == 0) || Criteres->Strings[0].IsEmpty())
                s += " 'Armoire';";
              if( (Criteres->Count <= 1) || Criteres->Strings[1].IsEmpty())
                s += " 'Rayon';";
              if( (Criteres->Count <= 2) || Criteres->Strings[2].IsEmpty())
                s += " 'Classeur';";
              if( (Criteres->Count <= 3) || Criteres->Strings[3].IsEmpty())
                s += " 'Dossier';";
              s.Delete(s.Length(),1);
              s += " ne sont pas paramétrés. Le classement automatique n'est pas possible pour cet état.";
              EICAttention( s);
              bResult = mrCancel;
            }
            else throw EUser( TAGL, "Trop de critères");
        }
      }
      delete Criteres;
    }
    if( bResult == mrNone)
    {
      //if( !frmEnvoiGED->pnlInfoClassAuto->Visible)
        //frmEnvoiGED->Height = frmEnvoiGED->Height - frmEnvoiGED->pnlInfoClassAuto->Height;

      /*if( NomDocument.IsEmpty())
      {
        frmEnvoiGED->pnlNomDoc->Visible = false;
        //frmEnvoiGED->Height = frmEnvoiGED->Height - frmEnvoiGED->pnlNomDoc->Height;
      }else*/
      {
        //frmEnvoiGED->m_asNomDoc = NomDocument;
        frmEnvoiGED->edDoc->Caption = NomDocument;
        frmEnvoiGED->rbPdfTouteSel->Enabled = pChoixClassementEnsDocsPossible;
        switch (pDestGEDPrecedent)
        {
          case 0:
          case 3:
            frmEnvoiGED->rbPDF->Checked = true;
            break;
          case 1:
            if (frmEnvoiGED->rbDestClasse->Enabled)
              frmEnvoiGED->rbDestClasse->Checked = true;
            break;
          case 2:
            if (frmEnvoiGED->rbDestPaniere->Enabled)
              frmEnvoiGED->rbDestPaniere->Checked = true;
            break;
        }
        switch(pChoixPossibles)
        {
          case 0 : //tous
            break;
          case 1 : // GED seulement
            frmEnvoiGED->rbPDF->Enabled = false;
            frmEnvoiGED->rbPDF->Checked = false;
            frmEnvoiGED->eRep->Enabled = false;
            frmEnvoiGED->Label7->Enabled = false;
            frmEnvoiGED->bOpenDir->Enabled = false;
            ASSERT(!pChoixClassementEnsDocsPossible);
            break;
          case 2 : //PDF seulement
            frmEnvoiGED->rbDestClasse->Enabled = false;
            frmEnvoiGED->rbDestClasse->Checked = false;
            frmEnvoiGED->rbDestPaniere->Enabled = false;
            frmEnvoiGED->rbDestPaniere->Checked = false;
            ASSERT(!pChoixClassementEnsDocsPossible);
            break;
        }
        if(!frmEnvoiGED->eRep->Text.IsEmpty() && frmEnvoiGED->rbPDF->Checked)
          frmEnvoiGED->btEnvoyer->Enabled = true;
        //frmEnvoiGED->edNomDoc->Text = frmEnvoiGED->m_asNomDoc;
        //frmEnvoiGED->rbDestClasse->Caption = "Classer dans GED'EIC";
        //frmEnvoiGED->rbDestPaniere->Caption = "Envoyer dans la panière";
      }

      if( hwndFenetreEICShell)
        SetWindowLong( frmEnvoiGED->Handle, GWL_HWNDPARENT, (long)hwndFenetreEICShell);
      bResult = frmEnvoiGED->ShowModal();
      if( bResult == mrOk)
      {
        bClassementAppliqueAuDocumentCourant = frmEnvoiGED->rbPdfEtat->Checked;
        NomDocument = frmEnvoiGED->edNomDoc->Enabled ? frmEnvoiGED->edNomDoc->Text : frmEnvoiGED->edDoc->Caption;
        bSepareImpGroupe = !frmEnvoiGED->cbFusion->Checked;
        if( frmEnvoiGED->rbDestClasse->Checked)
        {
          DestGED = 1;
          NomImprimante = GED_NomPilote();
          if (bClassementAppliqueAuDocumentCourant && bSepareImpGroupe)
            Classement = frmEnvoiGED->GetClassementGED();
          if( bCapture)
            GED_Capture( pvGedEIC, DestGED);

        }
        if( frmEnvoiGED->rbDestPaniere->Checked)
        {
          DestGED = 2;
          NomImprimante = GED_NomPilotePaniere();
        }
        if (frmEnvoiGED->rbPDF->Checked){
            DestGED = 3;
            Classement = IncludeTrailingBackslash(frmEnvoiGED->eRep->Text);
            ForceDirectories(Classement);
        }
      }
    }

    delete frmEnvoiGED;
  }
  catch( Exception &ex)
  {   EICDisplayException( TAGL, ex); bResult = false;
  }
  return bResult;
    }

//---------------------------------------------------------------------------
__fastcall TEnvoiGED::TEnvoiGED(TComponent* Owner, Variant *pvGedEIC)
  : TForm(Owner)
{
  rbPdfEtat->Checked = true;
  m_LstSelectionGED = new TStringList();
  lblDestPaniere->Caption = "Attention, avant d'effectuer l'envoi dans la panière, il faut veiller à "
                            "ce que la capture d'impression soit armée pour la panière de destination. \r\n"
                            "Pour ce faire, il faut cliquer sur le bouton 'Capture d'impression' de "
                            "la fenêtre de gestion des panières dans "NomAppliGED".";
  if(/*GED_gGestionEnvoi &&*/ GED_IsInstallee()){
      if(!pvGedEIC ||!CreationObjetGED(pvGedEIC)){
          rbDestClasse->Enabled = false;
          gbDest->Enabled = false;
          gbDest->ReadOnly = true;
          rbDestPaniere->Enabled = false;
          lblDestPaniere->Enabled = false;

          //this->Caption = "Impression en PDF";
          rbPDF->Checked = true;
      } else {
          //this->Caption = "Envoi dans GED'EIC";
          m_pvGedEIC = pvGedEIC;
          rbDestClick( NULL);
      }
  }else{
      rbDestClasse->Visible = false;
      gbDest->Visible = false;
      rbDestPaniere->Visible = false;
      pnlPaniere->Visible = false;
      rbPDF->Visible = false;
      //this->Caption = "Impression en PDF";
      this->Height = 250;
  }
  odChoixRep->RepertoireInitial = getenv("HOMEPATH");
  ChargerChemin(eRep->Items,GED_szCleRegLog);
  eRep->ItemIndex = 0;
//  m_vGedEICPaniere = Variant::CreateObject( "NovaPaniere.CNovaPaniere");
}
//---------------------------------------------------------------------------
__fastcall TEnvoiGED::~TEnvoiGED()
{
  delete m_LstSelectionGED;
//  m_vGedEICPaniere = Unassigned;
}
//---------------------------------------------------------------------------
void __fastcall TEnvoiGED::RefreshSelectionGED()
{
  m_LstSelectionGED->Clear();
  int nColonne = 0;

if( rbDestClasse->Checked)
  {
    for(int nColonne = 1;nColonne<=m_pvGedEIC->OlePropertyGet ("ColonneCount");nColonne++){
        m_LstSelectionGED->Add( m_pvGedEIC->OlePropertyGet ("Criteres", nColonne));
    }

    if( !(bool)m_pvGedEIC->OlePropertyGet ("DossierVisible") ||
        (m_pvGedEIC->OleFunction( "CriteresDossierEnCours") != m_LstSelectionGED->Text) )
    {
      m_pvGedEIC->OleFunction("ChargeDossier"); // permet de charger le dossier actif dans la grille
    }
    int Chemise = m_pvGedEIC->OlePropertyGet( "activechemise");
    if( Chemise < 0)
      m_LstSelectionGED->Add( EmptyStr);
    else
      m_LstSelectionGED->Add( m_pvGedEIC->OlePropertyGet ("TitreChemise", Chemise));
  }
  if( rbDestPaniere->Checked)
  {
//    m_LstSelectionGED->Add( m_vGedEICPaniere.OlePropertyGet ("Paniere"));
  }
}

//---------------------------------------------------------------------------
void __fastcall TEnvoiGED::btRefreshClick(TObject *Sender)
{
  RefreshSelectionGED();
  if( rbDestClasse->Checked)
  {
    edArmoire->Text       = m_LstSelectionGED->Strings[0];
    edRayon->Text         = m_LstSelectionGED->Strings[1];
    edClasseur->Text      = m_LstSelectionGED->Strings[2];

    if(m_pvGedEIC->OlePropertyGet("ColonneCount") == ColonneMaxGed){
        edIntercalaire->Text  = m_LstSelectionGED->Strings[3];
        edDossier->Text       = m_LstSelectionGED->Strings[4];
        edChemise->Text       = m_LstSelectionGED->Strings[5];
    }else{
        edDossier->Text       = m_LstSelectionGED->Strings[3];
        edChemise->Text       = m_LstSelectionGED->Strings[4];
    }
  }
//  if( rbDestPaniere->Checked)
//    edPaniere->Text  = m_LstSelectionGED->Strings[0];
}
//---------------------------------------------------------------------------

void __fastcall TEnvoiGED::btEnvoyerClick(TObject *Sender)
{
    try {
        if (eRep->Items->IndexOf(eRep->Text) == -1)
          eRep->Items->Insert(0,eRep->Text);
        SauvegarderChemin(eRep->Items,GED_szCleRegLog);

        if( rbDestClasse->Checked && edDossier->Text.IsEmpty())
        {
          EICAttention( "Il n'y a pas de dossier actif dans "NomAppliGED". Veuillez sélectionner un dossier dans "NomAppliGED" avant d'envoyer le document.");
          return;
        }

        AnsiString Destination = m_LstSelectionGED->CommaText;
        RefreshSelectionGED();
        if(rbDestClasse->Checked &&  m_LstSelectionGED->CommaText != Destination)
        {
          if( !EICQuestion( (AnsiString(
                                       "Le classement a changé dans "NomAppliGED".\r\n"
                                       "Le nouveau classement est :\r\n")+
                                       "\tArmoire : " + m_LstSelectionGED->Strings[0] + "\r\n"
                                       "\tRayon : " + m_LstSelectionGED->Strings[1] + "\r\n"
                                       "\tClasseur : " + m_LstSelectionGED->Strings[2] + "\r\n"
                                       "\tDossier : " + m_LstSelectionGED->Strings[3] + "\r\n" +
                                       (m_LstSelectionGED->Strings[4].IsEmpty()?EmptyStr:("\tChemise : " + m_LstSelectionGED->Strings[4] + "\r\n"))+
                                       "\r\n"
                                       "Voulez vous continuer ?").c_str(),
                                       "Attention"))
          {
            m_LstSelectionGED->CommaText = Destination;
            return;
          }
        }
    } catch(Exception &e) {
         EICDisplayException( TAGL, e); }
  ModalResult = mrOk;
}
//---------------------------------------------------------------------------
void __fastcall TEnvoiGED::rbDestClick(TObject *Sender)
{
  btRefresh->Enabled = rbDestClasse->Checked;
  btRefreshClick( btRefresh);
  if( !rbDestClasse->Checked)
  {
    edArmoire->Text      = EmptyStr;
    edRayon->Text        = EmptyStr;
    edClasseur->Text     = EmptyStr;
    if(m_pvGedEIC->OlePropertyGet("ColonneCount") == ColonneMaxGed)
        edIntercalaire->Text = EmptyStr;
    edDossier->Text      = EmptyStr;
    edChemise->Text      = EmptyStr;
  }
//  if( !rbDestPaniere->Checked)
//    edPaniere->Text  = EmptyStr;
    if(rbDestClasse->Checked || rbDestPaniere->Checked)
        btEnvoyer->Enabled = true;
  GestionActivationSaisieDuNomDuDocument();
}
//---------------------------------------------------------------------------

void __fastcall TEnvoiGED::bOpenDirClick(TObject *Sender)
{
    if(odChoixRep->Execute())
        eRep->Text = odChoixRep->Repertoire;
    eRepChange(NULL);
}
//---------------------------------------------------------------------------
void __fastcall TEnvoiGED::eRepChange(TObject *Sender)
{
    btEnvoyer->Enabled = (rbPDF->Checked && eRep->Text!=EmptyStr);
}
//---------------------------------------------------------------------------

void __fastcall TEnvoiGED::rbPdfEtatClick(TObject *Sender)
{
/*    if(rbPdfEtat->Checked == true)
        rbPdfTouteSel->Checked = false;
        edNomDoc->Text = EmptyStr;*/
        //edNomDoc->Enabled = false;
        //edDoc->Caption = EmptyStr;
}
//---------------------------------------------------------------------------

void __fastcall TEnvoiGED::rbPdfTouteSelClick(TObject *Sender)
{
    if(rbPdfTouteSel->Checked == true)
        rbPdfEtat->Checked = false;
        //edNomDoc->Enabled = true;
        //edNomDoc->Text = m_asNomDoc;
        //edDoc->Caption = m_asNomDoc;
}
/*---------------------------------------------------------------------------
            Fonction : ChargerChemin()
 Paramètres d'entrée : la liste de chemins à remplir
Paramètres de sortie : la liste de chemins sauvegardés
    Valeur retournée : Aucune
         Description : Permet de recuperer les chemins sauvegardés
                       dans la base de registre
//-------------------------------------------------------------------------*/
void __fastcall ChargerChemin( TStrings *lChemins,const AnsiString &asChemin )
{
    TStringList *lElem = NULL;
    TRegistry   *Reg   = NULL;
    try {
        lElem = new TStringList();
        Reg = new TRegistry();
        if (Reg->OpenKey(asChemin, true)) {
            Reg->GetValueNames(lElem);
            lChemins->Clear();
            for (int i=0; i<lElem->Count; i++) {
                lChemins->Add(Reg->ReadString(lElem->Strings[i]));
            }
            Reg->CloseKey();
        }
    } catch( Exception &e ) {
         EICDisplayException( TAGL, e); }
    if (Reg  ) { delete Reg  ; Reg   = NULL; }
    if (lElem) { delete lElem; lElem = NULL; }
}
/*---------------------------------------------------------------------------
            Fonction : SauvegarderChemin()
 Paramètres d'entrée : la liste de chemins à sauvegarder
Paramètres de sortie : Aucun
    Valeur retournée : Aucune
         Description : Permet de sauvegarder les derniers chemins de
                       sauvegarde ou de restauration dans la base de registre
//-------------------------------------------------------------------------*/
void __fastcall SauvegarderChemin( TStrings *lChemins,const AnsiString &asChemin )
{
    TRegistry *Reg = NULL;
    AnsiString asCle;
    try {
        if (lChemins->Count > 0) {
            Reg = new TRegistry();
            if (Reg->OpenKey(asChemin, true)) {
                for (int i=0; i<lChemins->Count && i<10 ; i++) {
                    asCle = AnsiString("SAVE") + i;
                    Reg->WriteString(asCle, lChemins->Strings[i]);
                }
                Reg->CloseKey();
            }
        }
    } catch( Exception &e ) {
        EICDisplayException( TAGL, e); }
    if (Reg  ) { delete Reg  ; Reg   = NULL; }
}
void __fastcall TEnvoiGED::rbPdfTouteSelCheck(TObject *Sender, bool bIsChecked)
{
  cbFusion->Enabled = bIsChecked;
  if (!bIsChecked)
    cbFusion->Checked = false;
  GestionActivationSaisieDuNomDuDocument();
}
//---------------------------------------------------------------------------
void __fastcall TEnvoiGED::cbFusionClick(TObject *Sender)
{
  GestionActivationSaisieDuNomDuDocument();
}
//---------------------------------------------------------------------------
void __fastcall TEnvoiGED::rbPdfEtatCheck(TObject *Sender, bool bIsChecked)
{
  GestionActivationSaisieDuNomDuDocument();
/*  if (bIsChecked)
    edNomDoc->Text = EmptyStr;*/
}
//---------------------------------------------------------------------------
AnsiString __fastcall TEnvoiGED::GetClassementGED()
{
  RefreshSelectionGED();
  return m_LstSelectionGED->CommaText;
}
//---------------------------------------------------------------------------
void __fastcall TEnvoiGED::GestionActivationSaisieDuNomDuDocument()
{
  edNomDoc->Enabled = cbFusion->Checked || (rbPdfEtat->Checked && (rbPDF->Checked || rbDestClasse->Checked));
  if (edNomDoc->Enabled)
  {
    if (rbPDF->Checked)
      edNomDoc->Text = edDoc->Caption + " - "+
                      (Date().FormatString("dd-mm-yyyy"))+ " - "+
                      (Time().FormatString("hh.nn.ss"));
    else if (rbDestClasse->Checked)
      edNomDoc->Text = edDoc->Caption;
  }
}
void __fastcall TEnvoiGED::rbPDFClick(TObject *Sender)
{
  GestionActivationSaisieDuNomDuDocument();
}
//---------------------------------------------------------------------------

void __fastcall TEnvoiGED::FormShow(TObject *Sender)
{
  GestionActivationSaisieDuNomDuDocument();  
}
//---------------------------------------------------------------------------

